<template>
	<view class="content">
		<uni-search-bar placeholder="请输入关键词搜索" class="uni-searchbar" cancelButton="none" radius="50" @confirm="search"
			@clear="clearKeyword" />
		<view v-if="blogs.length == 0" class="none">
			<image src="../../static/icons/nodata.png" mode="widthFix" class="logo"></image>
			<text class="title">抱歉,没有相关文章</text>
		</view>
		<view v-else class="item-container" v-for="(item,index) in blogs" :key="item.id" @click="gotoDetail(item.id)">
			<text class="item-title">{{item.title}}</text>
			<rich-text :nodes="item.description" class="item-desc"></rich-text>
			<image :src="item.picture" mode="widthFix" class="img item-pic"></image>
			<text class="iconfont icon-icon-test img-oper" @click="popSheet(item.id)"></text> <!-- 文本字体图标，不能用img标签，得使用text标签 -->
			<view>
				<text v-for="(tag,idx) in item.tags" :key="idx" class="item-tag">{{tag}}</text>
			</view>
			<image :src="item.user.avatar" mode="aspectFill" class="img-head" @click.stop="clickShowUser(item.user)"></image>
			<view class="icon-container">
				<!-- 由于changeGood在gotoDetail的内部，会引起事件冒泡，所以为了独立两个事件，在内侧的事件加上stop -->
				<text @click.stop="changeGood(item.id,true)" v-if="good_ids.indexOf(item.id) < 0" class="iconfont icon-good icon"></text>
				<text @click.stop="changeGood(item.id,false)" v-else class="iconfont icon-good-fill icon icon-good-yes"></text>
				<text class="icon-text">{{item.good}}</text>
				<text class="iconfont icon-icon-test3 icon"></text>
				<text class="icon-text">{{item.comments.length}}</text>
				<text class="iconfont icon-icon-test1 icon"></text>
				<text class="icon-text">{{item.readCount}}</text>
			</view>
		</view>
		<view class="buttom" v-if="blogs.length == count">到达底部/我是有底线的</view>
		<dialog-shell ref="shell" title="用户描述" @confirm = "confirmInfo">
			<text style="padding: 10rpx;font-size: 28rpx;">{{userDesc}}</text>
		</dialog-shell>
	</view>
</template>

<script>
	let page = 0 //当前页
	let size = 3 //每一页的大小
	let key_blogs = "blogs"
	export default {
		data() {
			return {
				blogs: [], //请求的数据存放的数组
				count: -1, //用于保存服务器返回的总数据条数
				searching: false ,//是否正在搜索
				good_ids:[],
				userDesc: ""
			}
		},
		onLoad() {  //页面加载
			this.$noti.add(this.$params.noti_refresh_count,this.notifyRefreshCount,this)  //页面加载时注册通知
			this.$noti.add(this.$params.noti_blog_goodcount, this, this.refreshgood)
			let ids = uni.getStorageSync(this.$params.key_good_ids)
			if(ids){
				this.good_ids = ids
			}
			let blogs = uni.getStorageSync(key_blogs)
			if (blogs) { //如果有本地数据使用本地数据
				this.blogs = blogs
				this.count = blogs.length
			} else {
				this.getPagedBlogs() //没有则使用服务器数据
			}
		},
		onUnload() {  //页面卸载
			this.$noti.remove(this.$params.noti_refresh_count)  //移除通知
			this.$noti.remove(this.$params.noti_blog_goodcount, this)
		},
		onPullDownRefresh() { //下拉刷新后初始化
			page = 0 //页数清零
			this.blogs = [] //数据清零
			this.count = -1 //总数返回初始值
			this.getPagedBlogs() //再次执行方法
		},
		onReachBottom() { //发起下一页请求的方法
			//搜索中禁用分页
			if (this.searching || this.blogs.length == this.count) {
				return
			}
			page += 1
			this.getPagedBlogs()
		},
		methods: {
			clickShowUser(user){
				this.userDesc = "作者：" + user.nickName + "\n联系方式" + user.email
				this.$refs.shell.show()
			},
			confirmInfo(){
				console.log("emit");
			},
			gotoDetail(id){
				uni.navigateTo({
					url: '../blog/blog?id=' + id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			notifyRefreshCount(info){
				let id = info.id
				let count = info.count
				this.refreshReadCount(id,count)
			},
			refreshReadCount(id,count){
				this.blogs.forEach(b => {
					if(b.id == id){
						b.readCount = count
					}
				})
			},
			changeGood(id,isGood){
				//TODO:同步到服务器，并且取最新数据
				let url = this.$params.host
				let action = isGood ? this.$params.action_good : this.$params.action_del_good
				url += action
				let data = {
					"id" : id
				}
				this.$request.postParam(url,data,res => {
					// console.log(res);
					this.blogs.forEach(blog => {
						if(blog.id == id){
							blog.good = res.data
						}
					})
					if (isGood) {
					    this.good_ids.push(id);
						// this.good_ids = this.good_ids.concat(id)
					  } else {
					    let index = this.good_ids.indexOf(id);
						
						//shift 删除第一个元素，pop删除最后一个元素。splice删除指定位置元素
						//pop，把最后一个元素替换要删除的元素，然后pop[1,2,3,4,5]
						//数组较大且顺序不影响程序功能时，可提高性能
						
					    // if (index >= 0) {
					    //   this.good_ids.splice(index, 1);
					    // }
						this.$util.remove(this.good_ids,index)
					  }
					uni.setStorageSync(this.$params.key_good_ids, this.good_ids);
				},() => {})
			},
			getPagedBlogs() { //服务器数据读取
				// console.log("开始分页请求");
				if(this.blogs.length == this.count){
					uni.showToast({
						title:"已经全部加载完成"
					})
					return
				}
				let header = {
					"content-type": "application/json;charset=UTF-8",
					"page": page,
					"size": size
				}
				this.$request.getWithHeader(this.$params.host + this.$params.action_blogs_page, header, res => { //使用实例
					res.data.forEach(blog => {
						if (!blog.picture.startsWith('http')) {
							blog.picture = 'https://1.12.223.54/' + blog.picture
						}
						blog.user.avatar = 'https://1.12.223.54/' + blog.user.avatar
					})
					this.blogs = [...this.blogs, ...res.data]
					uni.setStorageSync(key_blogs, this.blogs) //保存数据到本地
					this.count = parseInt(res.message)
				}, () => {
					uni.stopPullDownRefresh()
				})
			},
			search(e) { //搜索事件
				let kw = e.value
				if (kw.length > 0) {
					//1、清空列表数据
					this.blogs = []
					//2、重置count
					this.count = -1
					//3、发起请求：①、要在常量文件中添加搜索的地址(params.js)，②使用get方法发起请求，③请求的结果要处理
					let url = this.$params.host + this.$params.action_search + kw
					this.$request.get(url, res => {
						res.data.forEach(blog => {
							if (!blog.picture.startsWith('http')) {
								blog.picture = 'https://1.12.223.54/' + blog.picture
							}
							blog.user.avatar = 'https://1.12.223.54/' + blog.user.avatar
						})
						this.blogs = [...this.blogs, ...res.data]
					}, () => {
						this.searching = true //启用搜索中
					})
				}
			},
			clearKeyword() { //清除搜索框内容
				//1.初始化blogs
				this.blogs = []
				//2.初始化页码
				page = 0
				//3.重新开始分页请求
				this.getPagedBlogs()
				//清除以后停止搜索
				this.searching = false
			},
			popSheet(id){
				uni.showActionSheet({
					itemList: ["删除","收藏"],
					success: res => {
						if(res.tapIndex == 0){
							uni.showModal({
								title: '删除blog',
								content: '确认删除吗？',
								showCancel: true,
								cancelText: '算了',
								confirmText: '删除',
								success: res => {
									if(res.confirm){
										this.deletBlog(id)
									}
								},
								fail: () => {},
								complete: () => {}
							});
						} else {
							uni.showToast({
								title: '收藏成功'
							});
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			deletBlog(id){
				//todo:删除blog
				uni.showToast({
					title: '还未登陆，不能删除'
				});
			}
		}
	}
</script>

<style>
	@import url("index.css");
</style>